package cn.js.sangu.unitStore.utils;

import java.util.HashMap;
import java.util.Map;

public class MimeTypeUtil {

    // 创建一个静态的MIME类型映射
    private static final Map<String, String> MIME_TYPE_MAP = new HashMap<>();

    static {
        // 初始化常见的文件扩展名与MIME类型的对应关系
        MIME_TYPE_MAP.put("txt", "text/plain");
        MIME_TYPE_MAP.put("pdf", "application/pdf");
        MIME_TYPE_MAP.put("doc", "application/msword");
        MIME_TYPE_MAP.put("docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
        MIME_TYPE_MAP.put("xls", "application/vnd.ms-excel");
        MIME_TYPE_MAP.put("xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        MIME_TYPE_MAP.put("ppt", "application/vnd.ms-powerpoint");
        MIME_TYPE_MAP.put("pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation");
        MIME_TYPE_MAP.put("jpg", "image/jpeg");
        MIME_TYPE_MAP.put("jpeg", "image/jpeg");
        MIME_TYPE_MAP.put("png", "image/png");
        MIME_TYPE_MAP.put("gif", "image/gif");
        MIME_TYPE_MAP.put("zip", "application/zip");
        MIME_TYPE_MAP.put("rar", "application/x-rar-compressed");
        // 可以根据需要添加更多的文件类型
    }

    /**
     * 根据文件名获取MIME类型
     *
     * @param fileName 文件名（包含扩展名）
     * @return MIME类型，如果找不到则返回"application/octet-stream"（默认类型）
     */
    public static String getMimeType(String fileName) {
        if (fileName == null || fileName.isEmpty()) {
            return "application/octet-stream";
        }

        // 获取文件扩展名（假设扩展名在文件名的最后，且以'.'开头）
        int dotIndex = fileName.lastIndexOf('.');
        if (dotIndex == -1 || dotIndex == fileName.length() - 1) {
            return "application/octet-stream";
        }

        String extension = fileName.substring(dotIndex + 1).toLowerCase();
        return MIME_TYPE_MAP.getOrDefault(extension, "application/octet-stream");
    }
}
